<?php

namespace app\wechat\controller;

use app\wechat\controller\Openid;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
use think\Db;
use think\facade\Log;

class Msg
{

    public $openPlatform;
    public $openidRedis;

    public function __construct()
    {
        $this->openPlatform = app('wechat.open_platform');
        $this->openidRedis = new Openid();
    }

    // 公众号回调
    public function callback($appid)
    {
        // 获取msg
        $server = $this->openPlatform->server;
        $msg = $server->getMessage();

        // 获取公众号信息
        $gh_id = $msg['ToUserName'];
        $openid = $msg['FromUserName'];

        $this->openidRedis->add_openid($appid, $openid);

//        $authinfo = $this->openPlatform->getAuthorizer($appid)['authorization_info'];
//        $authappid = $authinfo['authorizer_appid'];
//        $authtoken = $authinfo['authorizer_refresh_token'];

//        $acc = Db::table('authorizers')->where('appid', $appid)->find();

//        $officaialAccount = $this->openPlatform->officialAccount($appid, $authtoken);
//        $officaialAccount = $this->openPlatform->officialAccount($appid, $acc['refresh_token']);

        // 使用
//        switch ($msg['MsgType']) {
//            case 'text':
//                $word = $msg['Content'];
//                if ($word == 'openid') {
//                    $officaialAccount->customer_service->message($msg['FromUserName'])->to($openid)->send();
//                }
//                break;
//            case 'event':
//                if ($msg['Event'] == 'subscribe') {
//                    $this->handlerSubscribe($appid, $officaialAccount, $openid);
//                }
//                break;
//        }
    }

    // 处理订阅事件
    public function handlerSubscribe($appid, $officaialAccount, $openid)
    {
        $acc = Db::table('authorizers')->where('appid', $appid)->find();
        $msg = Db::table('nx_imgtext_info')->where('category', $acc['category'])->select();
        foreach ($msg as $m) {
            $content = $this->handlerNews($m);
            $officaialAccount->customer_service->message($content)->to($openid)->send();
        }
    }

    // 处理图文信息拼接
    public function handlerNews($item)
    {
        $new = [
            new NewsItem([
                'title' => $item['title'],
                'description' => $item['desc'],
                'url' => $item['t_url'],
                'image' => $item['img_url'],
            ]),
        ];

        return new News($new);
    }

}
